//
//  WmcCameraSettingVM.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/4/1.
//

import UIKit
import YPBedrock
import RxRelay

public extension WmcButtonItemType {
    /// 相机设置
    enum CameraSettingCell: Int, CaseIterable {
        /// 二维码验证真实性
        case qrcodeVerify
        /// 保存无水印
        case saveNoneWatermarkImage
        /// 上传无水印
        case uploadNoneWatermarkImage
        /// 隐藏官方水印
        case hiddenOfficialMark
        /// 拍照后确认页
        case takePhotoToPreview
        /// 接受推送提醒
        case acceptPushRemind
        /// 辅助线样式
        case assistLineStyle

        /// 更新
        case appUpdate
        /// 更新带提示
        case appUpdateTips
        /// 服务
        case serviceAgreement
        /// 隐私
        case privacyAgreement
    }
}

extension WmcCameraSettingVM {
    /// 协议类
    struct Agreement {
        var urlStr: String
        var name: String

        var url: URL {
            return urlStr.yp.url
        }
    }

    /// 用户协议地址
    static var ServiceAgreement: Agreement {
        return .init(urlStr: "https://m.yupao.com/index/otheruseragreementcamera/",
                     name: "用户协议")
    }

    /// 隐私政策地址
    static var PrivacyAgreement: Agreement {
        return .init(urlStr: "https://h5hybridprod.yupaowang.com/article-out?id=1601458161456328784",
                     name: "隐私政策")
    }
}

extension WmcCameraSettingVM {
    class CellModel {
        // Lifecycle

        init(title: String,
             style: Style,
             rowHeight: CGFloat = 57,
             type: WmcButtonItemType.CameraSettingCell)
        {
            self.title = title
            self.style = style
            self.rowHeight = rowHeight
            self.type = type
        }

        // Internal

        enum Style {
            /// 箭头
            case arrow

            /// 纯文字
            case text(_ text: String,
                      color: UIColor = .wmc_grayH8_8A8A99,
                      font: UIFont,
                      direction: YPDirection)

            /// 纯开关
            case `switch`(_ isOn: Bool,
                          redPoints: Bool = false)

            /// 文字开关
            case textSwitch(_ text: String,
                            color: UIColor = .wmc_grayH8_8A8A99,
                            font: UIFont,
                            direction: YPDirection,
                            isOn: Bool,
                            redPoints: Bool = false)

            /// 标题后缀跟图片带文字
            case titleImageText(_ image: UIImage,
                                imageSize: CGSize,
                                text: String,
                                color: UIColor = .wmc_grayH8_8A8A99,
                                font: UIFont,
                                direction: YPDirection)
        }

        /// 标题
        var title: String
        /// 样式
        var style: Style
        /// 高度
        var rowHeight: CGFloat

        var type: WmcButtonItemType.CameraSettingCell
    }
}

// MARK: - [WmcCameraSettingVM]

class WmcCameraSettingVM: WmcBaseVM {
    // MARK: 其他

    /// 当前版本是否为最新版
    static var currentIsNewVersion: Bool?
    
    /// 二维码验证真实性item
    private lazy var qrcodeVerifyItem: WmcSettingSubTitleActionSwitchItem = {
        let item = WmcSettingSubTitleActionSwitchItem(title: "二维码")
        item.subTitle = "真实性验证"
        item.image = "icon_question_32".wmc_image
        let wh = 32.0.wmc_autoHor
        item.buttonSize = CGSize(width: wh, height: wh)
        item.isShowRedPoint = true
        item.switchAction = {
            [weak self] _item in
            guard let self = self else { return }
            self.updateSwitchSetting(type: .qrcodeVerify, isOn: !_item.isOn)
        }
        item.buttonAction = {
            [weak self] _item in
            guard let self = self else { return }
            if _item.isShowRedPoint {
                _item.isShowRedPoint = false
                WmcUserdefault.save(value: false, forKey: .Tips.CameraSetting.qrcodeVerifyRedPoint)
                self.reloadData.accept(())
            }
            self.pushQRCodeVerifyVC()
        }
        return item
    }()
    
    /// 保存无水印item
    private lazy var saveNoWatermarkItem: WmcSettingSubTitleSwitchItem = {
        let item = WmcSettingSubTitleSwitchItem(title: "拍照时保存无水印原图")
        item.subTitle = "1张无水印，1张有水印"
        item.switchAction = {
            [weak self] _item in
            guard let self = self else { return }
            self.updateSwitchSetting(type: .saveNoneWatermarkImage, isOn: !_item.isOn)
        }
        return item
    }()
    
    /// 上传无水印item
    private lazy var uploadNoWatermarkItem: WmcSettingSwitchItem = {
        let item = WmcSettingSwitchItem(title: "同步无水印图片到云相册")
        item.switchAction = {
            [weak self] _item in
            guard let self = self else { return }
            self.updateSwitchSetting(type: .uploadNoneWatermarkImage, isOn: !_item.isOn)
        }
        return item
    }()
    
    /// 隐藏官方水印item
    private lazy var hideOfficialItem: WmcSettingSwitchItem = {
        let item = WmcSettingSwitchItem(title: "隐藏官方水印")
        item.switchAction = {
            [weak self] _item in
            guard let self = self else { return }
            self.updateSwitchSetting(type: .hiddenOfficialMark, isOn: !_item.isOn)
        }
        return item
    }()
    
    /// 拍摄后手动确认item
    private lazy var takePhotoToPreviewItem: WmcSettingSwitchItem = {
        let item = WmcSettingSwitchItem(title: "拍摄后手动确认")
        item.switchAction = {
            [weak self] _item in
            guard let self = self else { return }
            self.updateSwitchSetting(type: .takePhotoToPreview, isOn: !_item.isOn)
        }
        return item
    }()
    
    /// 推送提醒item
    private lazy var pushRemindItem: WmcSettingSwitchItem = {
        let item = WmcSettingSwitchItem(title: "接收推送提醒")
        item.switchAction = {
            [weak self] _item in
            guard let self = self else { return }
            self.updateSwitchSetting(type: .acceptPushRemind, isOn: !_item.isOn)
        }
        return item
    }()
    
    
    /// 拍摄辅助线item
    private lazy var assistLineItem: WmcSettingContentItem = {
        let item = WmcSettingContentItem(title: "拍摄辅助线")
        item.content = "无"
        item.selectedAction = {
            [weak self] _ in
            guard let self = self else { return }
            self.assistLineItemClicked.accept(())
        }
        return item
    }()
    
    /// 检查更新item
    private lazy var appUpdateItem: WmcSettingContentItem = {
        let item = WmcSettingContentItem(title: "检查更新")
        item.content = "版本号v\(YPWmcManager.shared.version)"
        item.selectedAction = {
            [weak self] _ in
            guard let self = self else { return }
            WmcAppUpdateManager.CheckUpdate(showToast: true)
        }
        return item
    }()
    
    /// 新版本提示item
    private lazy var appUpdateTipItem: WmcSettingTipContentItem = {
        let item = WmcSettingTipContentItem(title: "检查更新")
        item.content = "版本号v\(YPWmcManager.shared.version)"
        item.image = "cameraSetting_ new_version".wmc_image
        item.imageSize = CGSizeMake(60, 30)
        return item
    }()
    
    /// 用户协议item
    private lazy var userProtocolItem: WmcSettingContentItem = {
        let title = Self.ServiceAgreement.name
        let item = WmcSettingContentItem(title: title)
        item.selectedAction = {
            [weak self] _ in
            guard let self = self else { return }
            self.pushWeb(title: title, urlStr: Self.ServiceAgreement.urlStr)
        }
        return item
    }()
    
    /// 隐私协议item
    private lazy var privacyProtocolItem: WmcSettingContentItem = {
        let title = Self.PrivacyAgreement.name
        let item = WmcSettingContentItem(title: title)
        item.selectedAction = {
            [weak self] _ in
            guard let self = self else { return }
            self.pushWeb(title: title, urlStr: Self.PrivacyAgreement.urlStr)
        }
        return item
    }()
    
    
    
    
    // MARK: 输出

    /// 数据列表
    let dataListRelay: BehaviorRelay<[WmcItemGroup]> = .init(value: [])
    /// 公众号关注状态
    var followState: WmcWechatFollowState?
    /// 公众号关注状态获取回调
    let followStateGot: PublishRelay<Void> = .init()
    /// 点击辅助线回调
    let assistLineItemClicked: PublishRelay<Void> = .init()
    /// 刷新页面
    let reloadData: PublishRelay<Void> = .init()
    
    /// 二维码验证开关变化
    let switchChanged: PublishRelay<(WmcButtonItemType.CameraSettingCell, Bool)> = .init()

    var cameraSettingDelegate: WmcCameraSettingDelegate? {
        return YPWmcManager.shared.uiDelegate.cameraSettingDelegate
    }

    static func cameraSettingDelegate() -> WmcCameraSettingDelegate? {
        return YPWmcManager.shared.uiDelegate.cameraSettingDelegate
    }

    static func g0_defaultList() -> [WmcButtonItemType.CameraSettingCell] {
        var group_0_defaultList: [WmcButtonItemType.CameraSettingCell] = [
            .qrcodeVerify, // 二维码验证真实性
            .saveNoneWatermarkImage, // 保存无水印
            .uploadNoneWatermarkImage, // 上传无水印
            .hiddenOfficialMark, // 隐藏官方水印
            .takePhotoToPreview, // 拍照后预览/手动确认
        ]

        // 追加条目
        group_0_defaultList.append(contentsOf: [
            .assistLineStyle, // 辅助线设置
        ])

        if let caseList = cameraSettingDelegate()?.settingFirstMenuCellList(.current,
                                                                            defaultList: group_0_defaultList)
        {
            group_0_defaultList = caseList
        }
        return group_0_defaultList
    }

    static func g1_defaultList() -> [WmcButtonItemType.CameraSettingCell] {
        var group_1_defaultList: [WmcButtonItemType.CameraSettingCell] = []
        if YPWmcManager.shared.isIndependentPage { // 独立包才有
            if let currentIsNewVersion = Self.currentIsNewVersion { // 网络请求已知
                if currentIsNewVersion { // 当前已经是最新版
                    group_1_defaultList.append(.appUpdate)
                } else { // 不是最新版，要显示提示
                    group_1_defaultList.append(.appUpdateTips)
                }
            } else { // 网络请求未知
                group_1_defaultList.append(.appUpdate)
            }
            // 协议
            group_1_defaultList.append(contentsOf: [
                .serviceAgreement, // 用户协议
                .privacyAgreement, // 隐私政策
            ])
        }
        // 追加条目
        group_1_defaultList.append(contentsOf: [
        ])
        if let caseList = cameraSettingDelegate()?.settingFirstMenuCellList(.current,
                                                                            defaultList: group_1_defaultList)
        {
            group_1_defaultList = caseList
        }
        return group_1_defaultList
    }

    /// 检查是否有某一种Cell，用于外部处理
    static func checkUseCell(type: WmcButtonItemType.CameraSettingCell) -> Bool {
        for cellType in g0_defaultList() {
            if cellType == type {
                return true
            }
        }
        for cellType in g1_defaultList() {
            if cellType == type {
                return true
            }
        }
        return false
    }

    /// 加载数据
    func loadList() {
        var groups: [WmcItemGroup] = []
        // 第一组============
        let group_0 = toItemList(caseList: Self.g0_defaultList())
        groups.append(group_0)

        // 第二组===============
        let group_1 = toItemList(caseList: Self.g1_defaultList())
        groups.append(group_1)
        
        // cell高度设置
        groups.forEach { group in
            group.items.forEach { item in
                item.rowHeight = 57.wmc_autoHor
            }
        }
        let mediumRowHeight = 79.wmc_autoHor
        saveNoWatermarkItem.rowHeight = mediumRowHeight
        qrcodeVerifyItem.rowHeight = mediumRowHeight

        // 通知刷新
        dataListRelay.accept(groups)

        if Self.currentIsNewVersion == nil { // 网络请求未知
            // 请求网络
            WmcAppUpdateManager.IsNewVersion { [weak self] isNew, _ in
                guard let weakSelf = self else { return }
                Self.currentIsNewVersion = isNew
                weakSelf.loadList()
            }
        }
    }

    /// 转换成Model实体
    func toItemList(caseList: [WmcButtonItemType.CameraSettingCell]) -> WmcItemGroup {
        let commonSettings = WmcPreferenceSettingsManager.shared.cameraSetting
        let group = WmcItemGroup()
        caseList.forEach { cas in
            switch cas {
            case .qrcodeVerify: // 二维码验证真实性
                var isShowRedPoints: Bool = true
                if let _isShowRedPoints: Bool = WmcUserdefault.object(forKey: .Tips.CameraSetting.qrcodeVerifyRedPoint) {
                    isShowRedPoints = _isShowRedPoints
                }
                qrcodeVerifyItem.isShowRedPoint = isShowRedPoints
                qrcodeVerifyItem.isOn = commonSettings.qrcodeVerify
                group.items.append(qrcodeVerifyItem)
                
            case .saveNoneWatermarkImage: // 拍照时保存无水印原图
                saveNoWatermarkItem.isOn = commonSettings.saveNoneWatermarkImage
                group.items.append(saveNoWatermarkItem)

            case .uploadNoneWatermarkImage: // 同步无水印图片到云相册
                if commonSettings.saveNoneWatermarkImage { // 开启了保存无水印
                    uploadNoWatermarkItem.isOn = commonSettings.uploadNoneWatermarkImage
                    group.items.append(uploadNoWatermarkItem)
                }
            case .hiddenOfficialMark: // 隐藏官方水印
                hideOfficialItem.isOn = commonSettings.hiddenOfficialMark
                group.items.append(hideOfficialItem)
            case .takePhotoToPreview: // 拍摄后手动确认
//                var isShowRedPoints: Bool = true
//                if let _isShowRedPoints: Bool = WmcUserdefault.object(forKey: .Tips.CameraSetting.takePhotoToPreviewCellPoint) {
//                    isShowRedPoints = _isShowRedPoints
//                }
//                takePhotoToPreviewItem.isShowRedPoint = isShowRedPoints
                takePhotoToPreviewItem.isOn = commonSettings.takePhotoToPreview
                group.items.append(takePhotoToPreviewItem)
                
            case .acceptPushRemind: // 接受推送提醒
                pushRemindItem.isOn = commonSettings.acceptPushRemind
                group.items.append(pushRemindItem)
                
            case .assistLineStyle: // 拍摄辅助线
                let rawValue = commonSettings.assistLineStyle
                let cas = WmcHomeControlAssistLineLayer.AssistLineStyle(rawValue: rawValue) ?? .none
                assistLineItem.content = cas.info.name
                group.items.append(assistLineItem)

            case .appUpdate: // 检查更新
                group.items.append(appUpdateItem)

            case .appUpdateTips: // 检查更新(新版本提示)
                group.items.append(appUpdateTipItem)

            case .serviceAgreement: // 用户协议
                group.items.append(userProtocolItem)

            case .privacyAgreement: // 隐私协议
                group.items.append(privacyProtocolItem)
            }
        }
        return group
    }

    /// 更新开关类设置
    func updateSwitchSetting(type: WmcButtonItemType.CameraSettingCell,
                             isOn: Bool)
    {
        let cameraSetting = WmcPreferenceSettingsManager.shared.cameraSetting
        switch type {
        case .qrcodeVerify:
            cameraSetting.qrcodeVerify = isOn
        case .saveNoneWatermarkImage:
            cameraSetting.saveNoneWatermarkImage = isOn
        case .uploadNoneWatermarkImage:
            cameraSetting.uploadNoneWatermarkImage = isOn
        case .hiddenOfficialMark:
            cameraSetting.hiddenOfficialMark = isOn
        case .takePhotoToPreview:
            // 保存红点状态
//            WmcUserdefault.save(value: false, forKey: .Tips.CameraSetting.takePhotoToPreviewCellPoint)
            cameraSetting.takePhotoToPreview = isOn
        case .acceptPushRemind:
            cameraSetting.acceptPushRemind = isOn
        default: break
        }
        WmcPreferenceSettingsManager.updateCameraSettings(model: cameraSetting)
        // 重新加载数据
        loadList()
        // 回调
        switchChanged.accept((type, isOn))
        
    }

    /// 更新拍摄辅助线设置
    func updateAssistLineStyle(_ style: WmcHomeControlAssistLineLayer.AssistLineStyle) {
        let cameraSetting = WmcPreferenceSettingsManager.shared.cameraSetting
        cameraSetting.assistLineStyle = style.rawValue
        WmcPreferenceSettingsManager.updateCameraSettings(model: cameraSetting)
        loadList()
    }
    
    /// 获取微信公众号关注状态
    func getWechatFollowState() {
        WmcCameraSettingAPI.getWechatFollowState().subscribe {
            [weak self] followState in
            guard let self = self else { return }
            self.followState = followState
            self.followStateGot.accept(())
        } onError: { error in
            WmcHudManager.toast(error)
        }.disposed(by: rx.disposeBag)
    }
}

extension WmcCameraSettingVM {
    

    /// 跳转web页面
    private func pushWeb(title: String, urlStr: String) {
        let vm = WmcWebVM()
        vm.urlString = urlStr
        vm.title = title
        WmcNavigatorManager.push(.web, parms: vm)
    }
    
    /// 跳转二维码验证页面
    private func pushQRCodeVerifyVC() {
        WmcNavigatorManager.push(.qrcodeVerify)
    }
    
}
